package Query;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import model.Visit;

import org.json.JSONException;
import org.json.JSONObject;

public class MapQuery {
	
	private MapQuery(){
		System.out.println("MapQuery Default Const running");
	}
	
	public static JSONObject queryAPI(final Visit the_visit){
		
		// The request also includes the userip parameter which provides the end
		// user's IP address. Doing so will help distinguish this legitimate
		// server-side traffic from traffic which doesn't come from an end-user.
		URL url = null;
		JSONObject json = null;

		System.out.println("queryAPI running");
		System.out.println("origins=" + the_visit.getOrigin());
		System.out.println("&destinations=" + the_visit.getDestination());

		try {
			/*
			url = new URL("http://maps.googleapis.com/maps/api/distancematrix/json?" +
					"origins=" + the_visit.getOrigin() +
					"&destinations=" + the_visit.getDestination() +
					"&units=imperial&&sensor=false");
			
			*/
			url = new URL("http://maps.googleapis.com/maps/api/distancematrix/json?" +
					"origins=Vancouver" +
					"&destinations=San%20Francisco" +
					"&mode=bicycling" +
					"&sensor=false");

			
			System.out.println("\nURL:\n" + url.toString()+"\n");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpURLConnection  connection = null;
		try {
			connection = (HttpURLConnection) url.openConnection();

		String line;
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			int i = 0;
			while((line = reader.readLine()) != null) {
			 builder.append(line);
			 i++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			json = new JSONObject(builder.toString());

	//		printJSON(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// now have some fun with the results...
		return json;
	}
	
	public static void printJSON(final JSONObject the_JSON){
		try {
			System.out.println(the_JSON.toString(4));
			the_JSON.get("");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
